package org.kfive.nova.hadoop;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/*
* Sort.java
* Created  by  dell
* Created on 2016/3/30 15:22
*/
public class Sort {

    public static class SortMapper extends Mapper<LongWritable,Text,IntWritable,IntWritable>{

        public void map(LongWritable key,Text value,Context context) throws IOException,InterruptedException{
            IntWritable intValue = new IntWritable(Integer.parseInt(value.toString()));
            context.write(intValue,new IntWritable(1));
        }
    }

    public static class SortReducer extends Reducer<IntWritable,IntWritable,IntWritable,IntWritable>{

        private static IntWritable count = new IntWritable(1);

        public void reduce(IntWritable key,Iterable<IntWritable> values,Context context)throws IOException,InterruptedException{

            for (IntWritable value : values){
                context.write(count,key);
                count = new IntWritable(count.get()+1);
            }
        }
    }

    public static void main(String[] args) throws Exception{
        if(args.length!=2){
            System.err.println("WordCount error : Illegal arguments");
            System.exit(-1);
        }

        Job job = new Job();
        job.setJarByClass(Sort.class);
        job.setJobName("Sort");

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setMapperClass(SortMapper.class);
        job.setReducerClass(SortReducer.class);

        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
